package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * @author 石小俊
 */
@WebServlet("/deleteById")
public class DeleteEmpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        System.out.println("即将删除的员工的编号为:"+id);

        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 通过JDBC实现删除功能
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","root");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();
            // 删除成功之后跳转到员工列表
            resp.sendRedirect("findAll");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
